package t20250320.Wc2.Wc;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.HeartbeatManagerOptions;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.sink.PrintSinkFunction;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Wc {

    public static void main(String[] args) throws Exception {

        Configuration flinkConf = new Configuration();
//        flinkConf.setString("rest.port","9091");
        flinkConf.setLong(HeartbeatManagerOptions.HEARTBEAT_TIMEOUT.key(), 3600000);
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(flinkConf);


        DataStreamSource<Integer> source = env.addSource(new RichSourceFunction<Integer>() {

            private boolean isRunning = true;
            private java.util.Random random = new java.util.Random();
            @Override
            public void run(SourceContext<Integer> ctx) throws Exception {
                while (isRunning) {
                    ctx.collect(random.nextInt()%100);
                    Thread.sleep(1000);
                }
            }

            @Override
            public void cancel() {
                isRunning = false;
            }
        });


        /**
         * id想通的OutputTag
         */
        OutputTag<String> out1 = new OutputTag<String>("outtag"){};
        OutputTag<String> out2 = new OutputTag<String>("outtag"){};

        SingleOutputStreamOperator<String> process = source.process(new ProcessFunction<Integer, String>() {
            @Override
            public void processElement(Integer value, ProcessFunction<Integer, String>.Context ctx, Collector<String> out) throws Exception {

                if (value % 2 == 0) {
                    ctx.output(out1, value + "_out1");
                } else {
                    out.collect(value + "__main");
                }
            }
        });

        process.addSink(new PrintSinkFunction<String>() {
            @Override
            public void invoke(String value, Context context) throws Exception {
                System.out.println("main:" + value);
            }
        });

        process.getSideOutput(out2).addSink(new PrintSinkFunction<String>() {
            @Override
            public void invoke(String value, Context context) throws Exception {
                System.out.println("out1:" + value);
            }
        });


        env.execute("app");
    }
}
